

import {
		HostName
	} from '@/common/config.js'
/*
	修改请求方式
*/
export default class Request {
	http(param) {
		var url = param.url,
			method = param.method,
			header = {},
			data = param.data || {},
			// uni.getStorageSync('token')
			// token = param.token || "",
			token = uni.getStorageSync('token') ? uni.getStorageSync('token') : '' ,
			hideLoading = param.hideLoading || false;
		//拼接完整请求地址
		if(param.url.slice(0,4) === 'http'){
			var requestUrl = url;
		}else{
			var requestUrl = operate.api() + url;
		}
		
		//请求方式
		if (!method) {
			method = "GET"
		} else {
			method = method.toUpperCase();
			if (method == "PUT") {
				header = {
					'content-type': "application/x-www-form-urlencoded",
					"HostName":uni.getStorageSync('shopinfo') ? uni.getStorageSync('shopinfo').hostName : ''
				};
			} else {
				header = {
					// 'content-type': "application/x-www-form-urlencoded"
					'content-type': "application/json",
					"HostName":uni.getStorageSync('shopinfo') ? uni.getStorageSync('shopinfo').hostName : ''
				};
			}
		}
		//配置 登录token
		if (token) {
			header = {
				'Authorization': "Bearer " + token,
				"HostName":uni.getStorageSync('shopinfo') ? uni.getStorageSync('shopinfo').hostName : ''
			};
		}
		//加载圈
		if (!hideLoading) {
			uni.showLoading({
				mask:true,
				title:'加载中...'
			})
		}
		//开始请求
		return new Promise((resolve, reject) => {
			uni.request({
				url: requestUrl,
				data: data,
				method: method,
				header: header,
				success: (res) => {
					if (res.statusCode == 401  ) {
						return uni.navigateTo({
							url: '/pages/index/index'
						})
					}
					// 判断 请求api 格式是否正确
					if (res.statusCode && res.statusCode != 200) {
						// uni.showToast({
						// 	title: "错误：" + res.errMsg,
						// 	icon: 'none'
						// });
						return;
					}
					
					// 将结果抛出
					if (res.data.code == 200){
						
						resolve(res.data)
						
					} else {
						
						reject(res.data.msg)
						uni.showToast({    
							title: "异常：" + res.data.msg,
							icon: 'none'
						});
					}
				},
				//请求失败
				fail: (e) => {
					uni.showToast({
						title: "请求失败：" + e.errMsg,
						icon: 'none'
					});
					reject(e);
				},
				complete() {
					// 隐藏加载
					if (!hideLoading) {
						uni.hideLoading();
					}
					return;
				}
			})
		})
	}
}